<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="block">
      资源名称：
      <el-input v-model="resourceQuery.example.name"
                placeholder="请输入角色名称搜索"
                style="width: 200px;"
                class="filter-item"
                @keyup.enter.native="fetchResource" />
      <el-button class="filter-item"
                 type="primary"
                 icon="el-icon-search"
                 round
                 @click="fetchResource">
        搜索
      </el-button>
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 icon="el-icon-refresh-left"
                 round
                 @click="reset">
        重置
      </el-button>
    </div>
    <!-- 统一操作 -->
    <div class="block">
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 icon="el-icon-plus"
                 round
                 @click="showDialog(null)">
        添加
      </el-button>
    </div>
    <el-table v-loading="listLoading"
              ref="resourceList"
              :data="resoList"
              element-loading-text="正在获取资源数据..."
              border
              fit
              max-height="630"
              highlight-current-row>
      <el-table-column label="Id"
                       align="center">
        <template slot-scope="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column label="资源名称"
                       align="center">
        <template slot-scope="{row}">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column label="资源代码"
                       align="center">
        <template slot-scope="{row}">
          {{ row.code }}
        </template>
      </el-table-column>
      <el-table-column label="url"
                       align="center">
        <template slot-scope="{row}">
          {{ row.url }}
        </template>
      </el-table-column>
      <el-table-column label="api"
                       align="center"
                       width="150">
        <template slot-scope="{row}">
          {{ row.api}}
        </template>
      </el-table-column>
      <!-- <el-table-column label="类型"
                       align="center">
        <template slot-scope="{row}">
          {{ row.type|typeFilter }}
        </template>
      </el-table-column> -->
      <el-table-column label="打开图标"
                       align="center">
        <template slot-scope="{row}">
          <svg-icon :icon-class="row.openIcon" />
        </template>
      </el-table-column>
      <el-table-column label="关闭图标"
                       align="center">
        <template slot-scope="{row}">
          <svg-icon :icon-class="row.closeIcon" />
        </template>
      </el-table-column>
      <el-table-column class-name="status-col"
                       label="状态"
                       align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.state | stateTagFilter">{{ row.state | stateFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       width="250"
                       label="操作">
        <template slot-scope="{row}">
          <el-button type="primary"
                     icon="el-icon-edit-outline"
                     round
                     @click="showDialog(row)">
            编辑
          </el-button>
          <el-button type="danger"
                     @click="deleteReso(row.id)"
                     icon="el-icon-delete"
                     round>
            删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination @size-change="changeSize"
                     @current-change="changePage"
                     :current-page="resourceQuery.pageNum"
                     :page-sizes="[5, 10, 15, 20]"
                     :page-size="resourceQuery.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="dialogobj.title"
               width="700px"
               :visible.sync="dialogobj.visiable">
      <el-form :model="dialogobj.resource"
               :inline="true"
               label-width="200px"
               ref="resoForm"
               :rules="formRules"
               style=" margin-left:50px;">
        <el-form-item label="名称："
                      prop="name">
          <el-input v-model="dialogobj.resource.name"></el-input>
        </el-form-item>
        <el-form-item label="url："
                      prop="url">
          <el-input v-model.trim="dialogobj.resource.url"></el-input>
        </el-form-item>
        <el-form-item label="api："
                      prop="api">
          <el-input v-model.trim="dialogobj.resource.api"></el-input>
        </el-form-item>
        <el-form-item label="资源代码："
                      prop="code">
          <el-input v-model.number="dialogobj.resource.code"></el-input>
        </el-form-item>
        <el-form-item label="请求方式："
                      prop="method">
          <el-select v-model="dialogobj.resource.method"
                     placeholder="请选择">
            <el-option v-for="(method,index) in methods"
                       :key="index"
                       :label="method"
                       :value="method">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="打开图标："
                      prop="openIcon">
          <svg-icon v-if="dialogobj.resource.closeIcon"
                    :icon-class="dialogobj.resource.openIcon" />
          <el-select v-model="dialogobj.resource.openIcon"
                     placeholder="请选择">
            <el-option v-for="icon in svgIcons"
                       :key="icon"
                       :label="icon"
                       :value="icon">
              <svg-icon :icon-class="icon" />{{icon}}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关闭图标："
                      prop="closeIcon">
          <svg-icon v-if="dialogobj.resource.closeIcon"
                    :icon-class="dialogobj.resource.closeIcon" />
          <el-select v-model="dialogobj.resource.closeIcon"
                     placeholder="请选择">
            <el-option v-for="icon in svgIcons"
                       :key="icon"
                       :label="icon"
                       :value="icon">
              <svg-icon :icon-class="icon" />{{icon}}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父节点Id："
                      prop="parentId">
          <el-input v-model.trim.number="dialogobj.resource.parentId"></el-input>
        </el-form-item>
        <el-form-item label="状态："
                      prop="state">
          <el-radio-group v-model="dialogobj.resource.state">
            <el-radio :label="0">
              <el-tag :type="0|stateTagFilter">隐藏</el-tag>
            </el-radio>
            <el-radio :label="1">
              <el-tag :type="1|stateTagFilter">可见</el-tag>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary"
                   @click="formHandler">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getResoList, deleteResoById, addReso, updateReso, checkUrl, checkApi, checkCode, exist } from '@/api/rmsResource'
import svgIcons from '@/icons/svg-icons'
export default {
  filters: {
    stateFilter (state) {
      const rstateMap = ['隐藏', '可见']
      return rstateMap[state]
    },
    stateTagFilter (stateId) {
      const stateMap = ['info', 'success']
      return stateMap[stateId]
    },
    typeFilter (type) {
      const typeMap = ['菜单', '按钮']
      return typeMap[type]
    }
  },
  data () {
    //url校验规则
    let validateUrl = (rule, url, callback) => {
      checkUrl({ url, id: this.dialogobj.resource.id }).then(res => {
        if (res.data) {
          callback([new Error('该url已被使用')]);
        } else {
          callback();
        }
      })
    }
    //api校验规则
    let validateApi = (rule, api, callback) => {
      checkApi({ api, id: this.dialogobj.resource.id }).then(res => {
        if (res.data) {
          callback([new Error('该api已被使用')]);
        } else {
          callback();
        }
      })
    }
    //资源代码校验规则
    let validateCode = (rule, code, callback) => {
      checkCode({ code, id: this.dialogobj.resource.id }).then(res => {
        if (res.data) {
          callback([new Error('该代码已被使用')]);
        } else {
          callback();
        }
      })
    }
    //父节点校验
    let validateParentId = (rule, id, callback) => {
      exist({ id }).then(res => {
        if (!res.data) {
          callback([new Error('对应节点不存在')]);
        } else {
          callback();
        }
      })
    }
    return {
      resourceQuery: {
        example: {
          name: null
        },
        pageSize: 10,
        pageNum: 1
      },

      depList: null,
      posList: null,
      resoList: null,
      formRules: {
        name: [
          { required: true, message: "请输入资源名称", trigger: "blur" },
          { max: 10, message: '资源名称最多10位', trigger: 'blur' },
          { pattern: /^((?!\'|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\<|\>|\{|\}|\[|\]|\||\\|\+|\_|\=|\-|\:|\"|\;|\'|\,|\.|\?|\/|\`|\~).){1,10}$/, message: '资源名称不能包含特殊字符', trigger: "blur" },
        ],
        url: [
          { required: true, message: "请输入url", trigger: "blur" },
          { max: 50, message: 'url最多50位', trigger: "blur" },
          { pattern: /^((?=[a-zA-Z0-9\-\/]).){1,50}$/, message: 'url只能包含数字、字母、"-"和"/"', trigger: "blur" },
          { validator: validateUrl, trigger: "blur" },
        ],
        api: [
          { required: true, message: "请输入api", trigger: "blur" },
          { max: 50, message: 'api最多50位', trigger: "blur" },
          { pattern: /^((?=[a-zA-Z0-9\-\/]).){1,50}$/, message: 'api只能包含数字、字母、"-"和"/"', trigger: "blur" },
          { validator: validateApi, trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入资源代码", trigger: "blur" },
          { pattern: /^[0-9]{4}$/, message: '资源代码只能由4位数字组成', trigger: "blur" },
          { validator: validateCode, trigger: "blur" },
        ],
        parentId: [
          { validator: validateParentId, trigger: "blur" },
        ],
        method: [
          { required: true, message: "请选择请求方式", trigger: "blur" },
        ],
        openIcon: [
          { required: true, message: "请选择打开图标", trigger: "blur" },
        ],
        closeIcon: [
          { required: true, message: "请选择关闭图标", trigger: "blur" },
        ],
        state: [
          { required: true, message: "请选择状态", trigger: "blur" },
        ]
      },

      svgIcons,
      listLoading: true,
      methods: ['GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'],
      total: 0,
      dialogobj: {
        title: '',
        isAdd: true,
        visiable: false,
        resource: {}
      },
      tablefilters: {
        depFilters: null,
        posFilters: null
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {//初始化页面
      this.fetchResource()
    },
    fetchResource () {//获取角色数据
      this.listLoading = true
      getResoList(this.resourceQuery).then(res => {
        this.resoList = res.data.records
        this.total = res.data.total
        this.listLoading = false
      })
    },
    deleteReso (id) {//删除资源
      this.$confirm('此操作将永久该资源及文件,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteResoById(id).then(response => {
          if (response.code == 200) {
            this.fetchResource()
            this.$message({
              type: 'success',
              message: response.message
            })
          }
        })
      }).catch(() => { })
    },
    changeSize (size) {//更改每页呈现数据
      this.resourceQuery.pageSize = size
      this.resourceQuery.pageNum = Math.min(Math.ceil(this.total / size), this.resourceQuery.pageNum)
      this.fetchResource()
    },
    changePage (num) {//换页
      this.resourceQuery.pageNum = num
      this.fetchResource()
    },
    reset () {//重置搜索框内容和表格内容
      this.resourceQuery.example.name = null
      this.fetchResource()
    },
    showDialog (resource) {//显示对话框
      if (resource == null) {
        this.dialogobj = { ...this.dialogobj, title: '添加资源', isAdd: true, resource: { state: 1 }, visiable: true }
      } else {
        this.dialogobj = { ...this.dialogobj, title: '修改资源', isAdd: false, resource, visiable: true }
      }
    },
    formHandler () {//新增或修改资源信息
      this.$refs.resoForm.validate(valid => {
        if (valid) {
          if (this.dialogobj.isAdd) {
            addReso(this.dialogobj.resource).then(res => {
              if (res.code == 200) {
                this.fetchResource()
                this.$message({
                  type: 'success',
                  message: res.message
                })
              } else {
                this.$message({
                  type: 'error',
                  message: '未知错误'
                })
              }
            })
          } else {
            updateReso(this.dialogobj.resource).then(res => {
              if (res.code == 200) {
                this.fetchResource()
                this.$message({
                  type: 'success',
                  message: res.message
                })
              } else {
                this.$message({
                  type: 'error',
                  message: '未知错误'
                })
              }
            })
          }
          this.hideDialog()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    hideDialog () {
      this.$refs.resoForm.clearValidate()
      this.dialogobj.visiable = false
    }
  },
  watch: {
    'dialogobj.visiable' (val) {
      if (!val) {
        this.$refs.resoForm.clearValidate()
      }
    }
  }
}
</script>